import React, { Component } from "react";
import "./App.css";
import Card from "./component/Card";

let open = true;
class App extends Component {
  state = {
    sourceArr: [],
    showArr: [],
    openOne: null,
    openTwo: null,
    step: 0
  };
  componentDidMount() {
    this.init();
  }

  clickAciton(index) {
    if (!open) {
      return;
    }
    let { showArr, openOne, openTwo } = this.state;
    if (showArr[index]) {
      return;
    }
    showArr[index] = true;
    if (openOne === null && openTwo === null) {
      this.setState({
        showArr,
        openOne: index
      });
    } else {
      open = false;
      this.setState(
        {
          showArr,
          openTwo: index
        },
        () => {
          setTimeout(() => {
            this.game();
          }, 500);
        }
      );
    }
  }

  game() {
    let { sourceArr, openOne, openTwo, showArr, step } = this.state;
    if (sourceArr[openOne] !== sourceArr[openTwo]) {
      showArr[openOne] = false;
      showArr[openTwo] = false;
      this.setState({
        showArr
      });
    } else {
      this.setState({
        step: ++step
      });
    }
    this.setState({
      openOne: null,
      openTwo: null
    });
    open = true;
  }

  init() {
    if (this.state.step > 0 && this.state.step < 8) {
      return;
    }
    const emoticon = ["🍌", "🍎", "🍐", "🍊", "🍉", "🍒", "🍓", "🍇"];
    let arr = [...emoticon, ...emoticon];
    let showArr = [];
    for (let i = 0; i < arr.length; i++) {
      const randomIndex = Math.round(Math.random() * (arr.length - 1 - i)) + i;
      [arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];
      showArr.push(false);
    }
    this.setState({
      sourceArr: arr,
      showArr,
      openOne: null,
      openTwo: null,
      step: 0
    });
  }
  render() {
    let { sourceArr, showArr, step } = this.state;
    return (
      <div className="App">
        <header className="App-header">记忆卡片</header>
        <section className="App-section">
          {sourceArr.map((item, index) => (
            <div key={item + index} onClick={() => this.clickAciton(index)}>
              <Card title={item} hideTitle={"❓"} show={showArr[index]} />
            </div>
          ))}
        </section>
        <footer className="App-footer">
          <div className="btn-init" onClick={() => this.init()}>
            {step < 1
              ? "加油哦"
              : step < 8
              ? "成功配" + step + "对"
              : "恭喜，点我重新开始游戏"}
          </div>
        </footer>
      </div>
    );
  }
}

export default App;
